package com.hzxy.yiyid.web.tool.ip;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName BaiduIpRegion
 * @Description TOOD
 * @Author RAICOM2023
 * @Date 2023/3/6 10:11
 * @Version 1.0
 **/
@Component
@ConfigurationProperties(prefix = "baidu")
@PropertySource("classpath:baidu.properties")
public class BaiduIpRegion {

    private static String accessKey ;

    private static String secretKey;

    @Value("${bd.ip.access.key}")
    public void setApiKey(String str) {
        accessKey = str;
    }
    @Value("${bd.ip.app.secret}")
    public void setSecretKey(String str) {
        secretKey = str;
    }

    public static List<String> getRegion(String ip){
        String path = "http://ipapi.api.bdymkt.com/ip2location/retrieve";
        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, path);
        request.setCredentials(accessKey, secretKey);
        request.addHeaderParameter("Content-Type", "application/json;charset=UTF-8");
        String jsonBody = "{\n  \"ip\": \""+ip+"\"\n}";
        request.setJsonBody(jsonBody);
        ApiExplorerClient client = new ApiExplorerClient(new AppSigner());
        ApiExplorerResponse response = client.sendRequest(request);
        String responseStr = response.getResult();
        JSONObject jsonObject =  JSON.parseObject(responseStr);
        List<String> list = new ArrayList<>();
        list.add(jsonObject.getString("province"));
        list.add(jsonObject.getString("city"));
        list.add(jsonObject.getString("county"));
        return list;
    }
}
